package com.example.duomeitijuhe.ui;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TableRow;
import android.widget.TextView;
import com.example.duomeitijuhe.R;
import com.example.duomeitijuhe.constant.FinalConstant;
import com.example.duomeitijuhe.db.OperateDatabase;
import com.example.duomeitijuhe.others.ActivityCollector;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;

import java.util.SortedSet;

/**
 * Created by Michael on 2014/10/13.
 */
public class SinaBindedActivity extends Activity implements View.OnClickListener{

    private final int TRUE = 1;
    private final int FALSE = 0;

    private Button sinaBindButton;
    private TableRow tableRow;
    private TextView dateText;
    private Button unbindSinaButton;
    private Button backButton;

    CommonsHttpOAuthConsumer httpOauthConsumer;
    OAuthProvider httpOauthprovider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.sina_bind);
        ActivityCollector.addActivity(this);
        initData();
        sinaBindButton.setOnClickListener(this);
        backButton.setOnClickListener(this);
    }


    public void changeView(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = TRUE;
                handler.sendMessage(message);
            }
        }).start();
    }
    public void initData(){
        sinaBindButton = (Button)findViewById(R.id.bind_sina_button);
        unbindSinaButton = (Button)findViewById(R.id.unbind_sina_button);
        dateText = (TextView)findViewById(R.id.date_text);
        tableRow = (TableRow)findViewById(R.id.date_row);
        backButton = (Button)findViewById(R.id.back_button);
    }

    public void sinaOauthInternet(){

        try{
            httpOauthConsumer = new CommonsHttpOAuthConsumer(FinalConstant.CONSUMER_KEY,FinalConstant.CONSUMER_SECRET);
            httpOauthprovider = new DefaultOAuthProvider("http://api.t.sina.com.cn/oauth/request_token","http://api.t.sina.com.cn/oauth/access_token","http://api.t.sina.com.cn/oauth/authorize");
            String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, FinalConstant.CALL_BACK_URL);
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
        }catch(Exception e){
            String s= e.getMessage();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.i("SinaBindedActivity","获取token");
        super.onNewIntent(intent);
        Uri uri = intent.getData();
        String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
        try {
            httpOauthprovider.setOAuth10a(true);
            httpOauthprovider.retrieveAccessToken(httpOauthConsumer,verifier);
        } catch (OAuthMessageSignerException ex) {
            ex.printStackTrace();
        } catch (OAuthNotAuthorizedException ex) {
            ex.printStackTrace();
        } catch (OAuthExpectationFailedException ex) {
            ex.printStackTrace();
        } catch (OAuthCommunicationException ex) {
            ex.printStackTrace();
        }
        SortedSet<String> user_id= httpOauthprovider.getResponseParameters().get("user_id");
        String userId=user_id.first();
        Log.i("sinaUserId: ",userId);
        String token = httpOauthConsumer.getToken();
        Log.i("sinaToken: ",token);
        //String userSecret = httpOauthConsumer.getTokenSecret();
        String platform = "sina";
        OperateDatabase operateDatabase = new OperateDatabase(SinaBindedActivity.this,1);
        operateDatabase.insertDbToken(platform,userId,token);
        changeView();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bind_sina_button:
                Log.i("SinaBindedActivity","点击按钮");
                sinaOauthInternet();
                break;
            case R.id.back_button:
                Intent intent = new Intent(SinaBindedActivity.this,PlatformBindActivity.class);
                startActivity(intent);
                break;
            case R.id.unbind_sina_button:
                break;
            default:
                break;
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case TRUE:
                    sinaBindButton.setVisibility(View.GONE);
                    tableRow.setVisibility(View.VISIBLE);
                    unbindSinaButton.setVisibility(View.VISIBLE);
                    long date = System.currentTimeMillis();
                    System.out.println("日期：" + date);
                    dateText.setText("KFAJSLDK");
                    break;
                case FALSE:
                    sinaBindButton.setVisibility(View.VISIBLE);
                    tableRow.setVisibility(View.GONE);
                    unbindSinaButton.setVisibility(View.GONE);


            }
        }
    };
}